/**
 * 系统变量面板组件 - 只显示系统变量
 */
import React from 'react';
import { Card, Space, Tag, Button, Tooltip, message } from 'antd';
import { CopyOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { getSystemVariables, type SystemVariable } from '@/services/systemVariables';

interface SystemVariablePanelProps {
  onVariableClick?: (variableName: string) => void;
  title?: string;
}

const SystemVariablePanel: React.FC<SystemVariablePanelProps> = ({
  onVariableClick,
  title = "系统变量",
}) => {
  const systemVariables = getSystemVariables();

  // 复制变量到剪贴板
  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text).then(() => {
      message.success('已复制到剪贴板');
    }).catch(() => {
      message.error('复制失败');
    });
  };

  // 处理复制变量
  const handleCopyVariable = (variableName: string, e: React.MouseEvent) => {
    e.stopPropagation();
    copyToClipboard(`{{${variableName}}}`);
  };

  // 获取字段类型颜色
  const getFieldTypeColor = (type: string) => {
    switch (type) {
      case 'string': return 'blue';
      case 'number': return 'green';
      case 'date': return 'orange';
      case 'datetime': return 'purple';
      default: return 'default';
    }
  };

  // 获取字段类型标签
  const getFieldTypeLabel = (type: string) => {
    switch (type) {
      case 'string': return '文本';
      case 'number': return '数字';
      case 'date': return '日期';
      case 'datetime': return '时间';
      default: return type;
    }
  };

  // 渲染变量项
  const renderVariableItem = (variable: SystemVariable) => (
    <div
      key={variable.name}
      className="variable-item"
      style={{
        padding: '12px',
        border: '1px solid #d9d9d9',
        borderRadius: '6px',
        marginBottom: '8px',
        cursor: 'pointer',
        transition: 'all 0.2s',
        backgroundColor: '#fafafa',
      }}
      onClick={() => {
        // 优先使用TinyMCE的全局插入方法
        if (window.insertVariableToTinyMCE) {
          window.insertVariableToTinyMCE(`{{${variable.name}}}`);
        } else {
          // 回退到原有方法
          onVariableClick?.(variable.name);
        }
      }}
      onMouseEnter={(e) => {
        e.currentTarget.style.backgroundColor = '#e6f7ff';
        e.currentTarget.style.borderColor = '#1890ff';
      }}
      onMouseLeave={(e) => {
        e.currentTarget.style.backgroundColor = '#fafafa';
        e.currentTarget.style.borderColor = '#d9d9d9';
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <Space>
          <ClockCircleOutlined style={{ color: '#52c41a' }} />
          <span style={{ fontWeight: 500 }}>{variable.display_name}</span>
          <Tag size="small" color={getFieldTypeColor(variable.field_type)}>
            {getFieldTypeLabel(variable.field_type)}
          </Tag>
          <Tag size="small" color="green">
            🔧系统
          </Tag>
        </Space>
        <Tooltip title="复制变量">
          <Button
            type="text"
            size="small"
            icon={<CopyOutlined />}
            onClick={(e) => handleCopyVariable(variable.name, e)}
          />
        </Tooltip>
      </div>
      
      {variable.description && (
        <div style={{ marginTop: '4px', fontSize: '12px', color: '#666' }}>
          {variable.description}
        </div>
      )}
      
      <div style={{ marginTop: '4px', fontSize: '11px', color: '#52c41a' }}>
        📌 系统变量：自动获取当前值
      </div>
      
      <div style={{ marginTop: '4px', fontSize: '11px', color: '#ccc', fontFamily: 'monospace' }}>
        {`{{${variable.name}}}`}
      </div>
      
      {variable.sample_value && (
        <div style={{ marginTop: '4px', fontSize: '11px', color: '#1890ff' }}>
          示例值: {variable.sample_value}
        </div>
      )}
    </div>
  );

  return (
    <Card 
      title={title} 
      size="small"
      style={{ height: '100%' }}
      bodyStyle={{ 
        padding: '12px',
        maxHeight: '600px',
        overflowY: 'auto'
      }}
    >
      <div style={{ marginBottom: '12px' }}>
        <Space direction="vertical" style={{ width: '100%' }}>
          <div style={{ fontSize: '12px', color: '#666' }}>
            系统变量会在发送时自动替换为当前值
          </div>
        </Space>
      </div>
      
      <div>
        {systemVariables.map(renderVariableItem)}
      </div>
      
      {systemVariables.length === 0 && (
        <div style={{ textAlign: 'center', color: '#999', padding: '20px' }}>
          暂无系统变量
        </div>
      )}
    </Card>
  );
};

export default SystemVariablePanel;
